<?php

namespace Warehouse\Model;

use Inbound\Model\CommoninterfaceModel;
use Inbound\Service\PrepareneedsService;
use Warehouse\Service\PublicdataService;

class StockOutModel extends CommoninterfaceModel
{
    //数据库对象
    public $deliveryorders = NULL;
    //出库表
    static $table = 'deliveryorders';
    //数据
    public $deliveryorders_data = NULL;
    //出库D
    public $deliveryorders_id;

    /**
     * @param string $table
     * @param array  $param
     */
    public function __construct($table = '',$param = array())
    {
        $this->deliveryorders = M(self::$table,'wms_',$this->_db);
        parent::__construct();
    }

    /**
     * @param array $_array
     * @return mixed
     * 过滤查询条件
     */
    public function get_deliveryorders_model(&$_array = array())
    {
        if($_array){
            $_array = array_filter($_array);
        }else{
            //$_array = array('status' => 10);
        }
        $_array = PrepareneedsService::trim_array($_array);
        foreach($_array as $key => $_arr){
            switch($key){
                case 'delivery_date_from':
                    $_array['delivery_date'][] = array(
                        'egt',
                        $_arr
                    );
                    unset($_array['delivery_date_from']);
                    break;
                case 'delivery_date_to':
                    $_array['delivery_date'][] = array(
                        'elt',
                        $_arr
                    );
                    unset($_array['delivery_date_to']);
                    break;
                case 'delivery_man':
                    $_array['delivery_man'] = PublicdataService::get_user_id(trim($_arr));
                   // unset($_array['purchase_id']);
                    break;
            }
        }
        return $this->deliveryorders->where($_array);
    }


    /**
     * @param array $_array
     * @param null  $model
     * @return mixed
     * 插入出库表===单个
     */
    public function add_deliveryorders_table($_array = array(),&$model = NULL)
    {
        $this->deliveryorders_id = $model->table($this->_db.'.wms_'.self::$table)
            ->add($_array);
        return $this->deliveryorders_id;
    }

    /**
     * @param array $_array
     * @param null  $model
     * @return mixed
     * 插入出库表====批量
     */
    public function addall_deliveryorders_table($_array = array(),&$model = NULL)
    {
        return $this->deliveryorders_id = $model->table($this->_db.'.wms_'.self::$table)
            ->addAll($_array);
    }

    /**
     *更新操作
     */
    public function update_deliveryorders($_array = array(),$data = array(),&$model = NULL)
    {
        $model = $model==NULL?$this->deliveryorders:$model->table($this->_db.".wms_".self::$table);
        $res   = $model->where($_array)
            ->save($data);
        return $res;
    }

    /**
     * 计算实际库存量
     * @param array sku
     * @return array
     */
    public function get_inventory(array $skus = NULL)
    {
        if($skus){
            $skus_string = "";
            foreach($skus as $sku){
                $skus_string .= $skus_string?",'".$sku."'":"'".$sku."'";
            }

            $date = date('Y-m-d');;
            $sql_string = "select upper(sku) as sku,sum(num) as inventory from (
	SELECT
		_wms_warehouseorders.sku AS sku,
		wms_warehouseorders.warehouse_quantity AS num
	FROM
		wms_warehouseorders
	WHERE
		wms_warehouseorders.warehouse_date >= DATE_FORMAT('".$date."', '%Y-%m-01')
    UNION ALL
		SELECT
			`wms_deliveryorders`.`sku` AS `sku` ,- (
				`wms_deliveryorders`.`quantity`
			) AS `num`
		FROM
			`wms_deliveryorders`
		WHERE
			`wms_deliveryorders`.`delivery_date` >= DATE_FORMAT('".$date."', '%Y-%m-01')

    UNION ALL

		SELECT
			`wms_inventories`.`sku` AS `sku`,
			`wms_inventories`.`quantity` AS `num`
		FROM
			`wms_inventories`
		WHERE
			`wms_inventories`.`inventory_date` = DATE_FORMAT('".$date."', '%Y-%m-01')
	) a where sku in (".$skus_string.") GROUP BY sku";

            $re = $this->deliveryorders->execute($sql_string);
            $inventory = array();
            if($re){
                foreach($re as $value){
                    $inventory[$value['sku']] = $value['inventory'];
                }
            }
            return $inventory;
        }
    }

    /**
     * 非出口退税
     * 获取当月出库数量
     * @param $sku
     * @return mixed
     */
    public function getSkuDeliveryCount(&$_array)
    {
        $model = $this->deliveryorders;
        $where_map = array(
            'sku'               => $_array['sku'],
            'enterprise_dominant'               => $_array['enterprise_dominant'],
            'site_id'=> $_array['site_id'],
            'delivery_date'    => array( 'EGT', date( 'Y-m-01', time() ) ),
            'export_tax_rebate' => 0,
        );
        $res = $model->where($where_map)
            ->field('SUM(quantity) as do_num, SUM(cost) AS cost')
            ->find();
        return $res;
    }

    /**
     * 出口退税
     * 获取当月出库数量
     * @param $sku
     * @return mixed
     */
    public function getTaxSkuDeliveryCount(&$_array)
    {
        $model = $this->deliveryorders;
        $where_map = array(
            'sku'               => $_array['sku'],
            'site_id'=> $_array['site_id'],
            'enterprise_dominant'               => $_array['enterprise_dominant'],
            'delivery_date'    => array( 'EGT', date( 'Y-m-01', time() ) ),
            'export_tax_rebate' => 1,
        );
        $res = $model->where($where_map)
            ->field('SUM(quantity) as do_num, SUM(cost) AS cost')
            ->find();
        return $res;
    }
    /**
     * @return mixed
     * 获取出库单指定月sku可用库存
     * khq 2017.4.28
     */
    public function get_qichu_out(){
        
        $starttime = date('Y-m-01', strtotime('-1 month'));
        $endtime   = date('Y-m-t', strtotime('-1 month'));
        $where['delivery_date'][] = array('EGT',$starttime);
        $where['delivery_date'][] = array('ELT',$endtime.' 23:59:59');
        return $this->deliveryorders->group( 'sku,enterprise_dominant,export_tax_rebate,site_id')
            ->where($where)
            ->where(array('type'=>array( 'eq', 10 )))
            ->field(
                'sku,enterprise_dominant,export_tax_rebate,site_id,
                SUM(quantity) AS all_quantity,SUM(cost) AS all_cost'
            )
            ->select();
    }

    /**
     * 描述：根据SKU、主体、入库类型获取当月出库成本
     * 作者：橙子
     */
    public function get_month_out($where) {
        $_where = array();

        $starttime = date('Y-m-01', strtotime('-1 month'));
        $endtime   = date('Y-m-t', strtotime('-1 month'));

        if ($where['warehouse_date']) {
            $starttime = date('Y-m-01', strtotime($where['warehouse_date']));
            $endtime   = date('Y-m-t', strtotime($where['warehouse_date']));

        }

        $_where['delivery_date'][] = array('EGT', $starttime);
        $_where['delivery_date'][] = array('ELT', $endtime.' 23:59:59');
        $where['sku'] && $_where['sku'] = $where['sku'];
        $where['enterprise_dominant'] && $_where['enterprise_dominant'] = $where['enterprise_dominant'];

        $result = $this->deliveryorders->field('sku,enterprise_dominant,sku_name,
        SUM(quantity) AS totalQuantity,SUM(cost) AS totalCost,type')
            ->group('sku,enterprise_dominant,type')
            ->order('')
            ->where($_where)
            ->select();

        return empty($result) ? array() : $result;
    }

    /**
     * 描述：计算下个期初的上个月出库数据
     */
    public function crontab_month_out() {
        $starttime = date('Y-m-01', strtotime('-1 month'));
        $endtime   = date('Y-m-t', strtotime('-1 month'));

        $_where['delivery_date'][] = array('EGT', $starttime);
        $_where['delivery_date'][] = array('ELT', $endtime.' 23:59:59');
        $result = $this->deliveryorders->field('sku,enterprise_dominant,sku_name,
        SUM(quantity) AS totalQuantity,SUM(cost) AS totalCost')
            ->group('sku,enterprise_dominant')
            ->order('')
            ->where($_where)
            ->select();

        return empty($result) ? array() : $result;
    }
}